using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace ctsu.Data
{
	public class DataAccess
	{
		public DataAccess()
		{
		}

		public static SqlConnection GetSqlConnection()
		{
			Database db = DatabaseFactory.CreateDatabase();
			return (SqlConnection)db.CreateConnection();
		}


		public static void AddParamArrayToDbCommand(DbCommand cmd, SqlParameter[] aParams)
		{
			foreach (SqlParameter param in aParams)
			{
				cmd.Parameters.Add(param);
			}
		}

		public static DataSet GetDataSet(string sql)
		{
			DataSet ds = null;
			Database db = DatabaseFactory.CreateDatabase();

			DbCommand dbc = db.GetSqlStringCommand(sql);
			ds = db.ExecuteDataSet(dbc);
			return ds;
		}

		public static DataSet GetDataSet(string sql, SqlParameter[] aParams)
		{
			DataSet ds = null;
			Database db = DatabaseFactory.CreateDatabase();

			DbCommand dbc = db.GetSqlStringCommand(sql);
			AddParamArrayToDbCommand(dbc, aParams);
			ds = db.ExecuteDataSet(dbc);
			return ds;
		}

		public static DataSet GetDataSet(CommandType cmdType, string spName)
		{
			Database db = DatabaseFactory.CreateDatabase();
			return db.ExecuteDataSet(cmdType, spName);
		}

		public static IDataReader GetDataReader(string spName, object[] aParams)
		{
			//caller must close datareader
			IDataReader idr = null;
			Database db = DatabaseFactory.CreateDatabase();

			//DbCommand dbc = db.GetSqlStringCommand(sql);
			idr = db.ExecuteReader(spName, aParams);
			return idr;
		}

		public static IDataReader GetDataReader(CommandType cmdType, string spName)
		{
			//caller must close datareader
			IDataReader idr = null;
			Database db = DatabaseFactory.CreateDatabase();

			//DbCommand dbc = db.GetSqlStringCommand(sql);
			idr = db.ExecuteReader(cmdType, spName);
			return idr;
		}

		public static IDataReader GetDataReader(string sql)
		{
			//caller must close datareader
			IDataReader idr = null;
			Database db = DatabaseFactory.CreateDatabase();

			DbCommand dbc = db.GetSqlStringCommand(sql);
			idr = db.ExecuteReader(dbc);
			return idr;
		}

		public static object GetScalarObject(CommandType commandType, string sql)
		{
			Database db = DatabaseFactory.CreateDatabase();
			return db.ExecuteScalar(commandType, sql);
		}

		public static int ExecuteNonQuery(CommandType commandType, string sql)
		{
			Database db = DatabaseFactory.CreateDatabase();
			return db.ExecuteNonQuery(commandType, sql);
		}
	}
}
